<template>
  <div class="loanBusiness">
    <Tabs :option="tabsOption" @change="tabsChange" />
    <div v-for="(item,index) in tabsOption.column" :key="index">
      <div v-if="changeTabOption.prop === item.prop">
        <div v-for="(item2, index2) in item.type" :key="item.prop + index2">
          <SimpleData
            v-if="item2 === 'simpleData'"
            :simple-data="simpleData"
            :option="simpleOption"
            :button-self="simpleButtonArray"
            @selfButton="simpleButton"
          />
          <avue-crud
            v-if="item2 === 'table'"
            :key="index2"
            :option="tableOption"
            :data="tableData"
            :page="tablePage"
            @search-change="search"
            @search-reset="searchClear"
            @size-change="sizeChangeSearch"
            @current-change="currentChangeSearch"
          >
            <template slot="menu" slot-scope="scope" style="float: right">
              <el-button
                v-for="(item,index) in tableButtonArray"
                :key="'cc' + index"
                size="small"
                type="text"
                @click="tableButton(item.prop, scope.row)"
              >{{ item.label }}
              </el-button>
            </template>
          </avue-crud>
        </div>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      top="5%"
      width="90%"
    >
      <el-scrollbar style="height: 450px;">
        <SimpleData
          v-if="dialogTableFlag === 'simpleData'"
          :simple-data="dialogSimpleData"
          :option="dialogSimpleOption"
          :button-self="dialogSimpleButtonArray"
          @selfButton="simpleButton"
        />
        <avue-crud
          v-if="dialogTableFlag === 'table'"
          :key="mathRandom"
          style="margin: 10px 0px;"
          :option="dialogTableOptions"
          :data="dialogTableData"
          :page="dialogTablePage"
          @search-change="dialogSearch"
          @search-reset="dialogSearchClear"
          @size-change="dialogSizeChange"
          @current-change="dialogCurrentChange"
        >
          <template slot="expand" slot-scope="{row}">
            短信内容：{{ row.content }}
          </template>
        </avue-crud>
        <div v-if="dialogTableFlag === 'form'">
          <avue-form ref="form" v-model="selectVal" :option="dialogFormOption" />
          <el-radio-group v-model="content">
            <el-radio
              v-for="(item3, index3) in msgTemplate"
              :key="index3"
              :label="item3.content"
              class="el-formMsg-radio"
              style="margin: 10px 0px;"
            >{{ item3.content }}</el-radio>
          </el-radio-group>
        </div>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="dialogTableFlag === 'form'" type="primary" @click="dialogSendMessage">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Axios from 'axios'
import Tabs from '@/components/common/Tabs'
import SimpleData from '@/components/common/SimpleData'
import { queryLoss, sendContentMessage } from '@/api/bankBiz/loss/loss'
import { messageTemplate, saveShortMessage, getShortMessage } from '@/api/bankBiz/personal/personInfo'

export default {
  name: 'ShortMessage',
  components: {
    Tabs,
    SimpleData
  },
  data() {
    return {
      namespace: 'Personal',
      nameFlag: 'sendShortMessage',
      type: [],
      returnType: [],
      tabsOption: {},
      changeTabOption: {},
      tableOption: {},
      tableButtonArray: [],
      tablePage: {},
      query: {
        'namespace': '',
        'key': ''
      },
      tableTotalData: [],
      tableData: [],
      // 表单相关
      simpleData: {},
      simpleOption: {},
      simpleButtonArray: [],
      // 详情相关
      dialogVisible: false,
      dialogTitle: '',
      dialogOption: {},
      dialogTableFlag: '',
      dialogSimpleData: {},
      dialogSimpleOption: {},
      dialogSimpleButtonArray: [],
      dialogTableData: [],
      dialogTableOptions: {},
      dialogTablePage: {
        'pageSizes': [20, 30, 50, 100],
        'currentPage': 1,
        'total': 0,
        'pageSize': 20
      },
      mathRandom: '',
      shortHistoryParams: {
        'currentPage': 1,
        'pageSize': 20
      },
      dialogFormOption: {},
      selectVal: {},
      msgTemplate: [],
      content: ''
    }
  },
  watch: {
    'selectVal.businessType': {
      handler(val) {
        if (val != '' && val != undefined && val != null) {
          this.content = ''
          this.msgTemplate = []
          this.getMessageTemplate(val)
        }
      },
      immediate: true
    }
  },
  created() {
    this.initOptions()
  },
  mounted() {

  },
  methods: {
    // 初始化配置
    initOptions() {
      this.type = this.$route.meta.type
      // 循环组件，初始化赋值
      for (let i = 0; i < this.type.length; i++) {
        // 1 页签初始化
        if (this.type[i] === 'tabs') {
          const tabsViewOption = personalOptions.tabsViewOption
          this.tabsOption = tabsViewOption[this.nameFlag].tabsOption
          // 默认第一个页签
          this.changeTabOption.prop = this.tabsOption.column[0].prop
          this.returnType = this.tabsOption.column[0].type
          // 详情相关
          this.dialogOption = this.tabsOption.column[0].detailOptions
          this.dialogSimpleButtonArray = this.tabsOption.column[0].detailOptions.simpleButtonArray

          // 初始化第一个页签配置
          for (let j = 0; j < this.tabsOption.column[0].type.length; j++) {
            if (this.tabsOption.column[0].type[j] == 'table') {
              this.tableOption = this.tabsOption.column[0].tableOptions
              this.tablePage = this.tabsOption.column[0].tablePage
              this.tableButtonArray = this.tabsOption.column[0].tableButtonArray
            } else if (this.tabsOption.column[0].type[j] == 'simpleData') {
              this.simpleOption = this.tabsOption.column[0].simpleOptions
              this.simpleButtonArray = this.tabsOption.column[0].simpleButtonArray
            }
          }
          if (this.tabsOption.column[0].query) {
            this.query.query = Object.assign({}, this.tabsOption.column[0].query)
          }
          this.query.namespace = this.namespace
          this.query.key = this.tabsOption.column[0].prop
        }
      }
      this.commonQueryData()
    },
    // 切换页签
    tabsChange(column) {
      console.log(column)
      let data = []
      for (let i = 0; i < this.tabsOption.column.length; i++) {
        if (this.tabsOption.column[i].prop === column.prop) {
          data = this.tabsOption.column[i]
        }
      }
      this.changeTabOption = data
      this.returnType = data.type
      if (data.query) {
        this.query.query = Object.assign({}, data.query)
      }
      this.query.key = data.prop
      // 详情相关
      this.dialogOption = data.detailOptions
      this.dialogSimpleButtonArray = data.detailOptions.simpleButtonArray
      for (let i = 0; i < data.type.length; i++) {
        if (data.type[i] == 'table') {
          this.tableOption = data.tableOptions
          this.tablePage = data.tablePage
          this.tableButtonArray = data.tableButtonArray
          this.tableData = []
          this.tableTotalData = []
        } else if (data.type[i] == 'simpleData') {
          this.simpleOption = data.simpleOptions
          this.simpleButtonArray = data.simpleButtonArray
        }
      }
      this.commonQueryData()
    },
    // 搜索按钮事件
    search(params, done) {
      Object.keys(params).forEach(keys => {
        if (params[keys]) {
          this.query.query[keys] = params[keys]
        }
      })
      this.commonQueryData(true)
      if (done) {
        done()
      }
    },
    searchClear() {
      this.query.query.accountNo = ''
    },
    // 调用接口获取数据
    commonQueryData(flag) {
      // 初始化接口入参
      if (this.query.query.customerNo) {
        this.query.query.customerNo = sessionStorage.getItem('customerNo')
      }
      if (this.query.query.accountNo && !flag) {
        this.query.query.accountNo = ''
      }
      // 初始化分页参数
      this.query.query.currentPage = 1
      this.query.query.pageSize = 20
      this.tablePage.currentPage = 1
      this.tablePage.pageSize = 20
      this.tablePage.total = 0
      // 短消息发送
      if (this.query.key == 'sendShortMessageData') {
        this.simpleData = {
          'customerName': sessionStorage.getItem('accName'),
          'idType': sessionStorage.getItem('customerIdType'),
          'idNo': sessionStorage.getItem('customerIdNo'),
          'accountNo': sessionStorage.getItem('bankNo'),
          'phone': sessionStorage.getItem('customerPhone')
        }
        return
      }
      // 调用公共业务接口
      queryLoss(this.query).then((res) => {
        console.log('response data is: ' + JSON.stringify(res.data))
        if (res.data.code == 200) {
          for (let i = 0; i < this.returnType.length; i++) {
            if (this.returnType[i] == 'table') {
              if (res.data.data.resList == null || res.data.data.resList == undefined) {
                this.tableData = []
                this.tableTotalData = []
                this.tablePage.total = 0
                return
              }
              this.tableData = res.data.data.resList
              this.tableTotalData = res.data.data.resList
              // 理财产品超市、当前持有、当前委托、基金产品超市
              if (this.query.key == 'wealthProductSupermarket') {
                console.log(parseInt(res.data.data.totalNum))
                this.tablePage.total = parseInt(res.data.data.totalNum)
                return
              }
              // 兼容客户端分页
              if (window.Settings.pageType == 'Client') {
                this.tableData = this.tableTotalData.slice((this.tablePage.currentPage - 1) * this.tablePage.pageSize, this.tablePage.currentPage * this.tablePage.pageSize)
                this.tablePage.total = this.tableTotalData.length
              }
            } else if (this.returnType[i] == 'simpleData') {
              this.simpleData = res.data.data
            }
          }
        } else {
          const errMsg = res.data.message
          window.globalUiKit.notify('提示', errMsg, 'error')
          this.tableData = []
          this.tableTotalData = []
          this.tablePage.total = 0
        }
      }).catch((err) => {
        this.tableData = []
        this.tableTotalData = []
        this.tablePage.total = 0
        console.log(err)
      })
    },
    // 切换行数
    sizeChangeSearch(val) {
      this.query.query.currentPage = 1
      this.query.query.pageSize = val
      // 理财产品超市、当前持有、当前委托、基金产品超市
      if (this.query.key == 'wealthProductSupermarket') {
        queryLoss(this.query).then((res) => {
          this.tablePage.total = parseInt(res.data.data.totalNum)
          this.tableData = res.data.data.resList
        }).catch((err) => {
          console.log(err)
        })
        return
      }
      // 兼容客户端分页
      if (window.Settings.pageType == 'Client') {
        this.tablePage.currentPage = 1
        this.tablePage.pageSize = val
        this.tableData = this.tableTotalData.slice((this.tablePage.currentPage - 1) * this.tablePage.pageSize, this.tablePage.currentPage * this.tablePage.pageSize)
        this.tablePage.total = this.tableTotalData.length
        return
      }
    },
    // 切换页码
    currentChangeSearch(val) {
      this.query.query.currentPage = val
      console.log('切换页码')
      // 理财产品超市、当前持有、当前委托、基金产品超市
      if (this.query.key == 'wealthProductSupermarket') {
        queryLoss(this.query).then((res) => {
          this.tablePage.total = parseInt(res.data.data.totalNum)
          this.tableData = res.data.data.resList
        }).catch((err) => {
          console.log(err)
        })
        return
      }
      // 兼容客户端分页
      if (window.Settings.pageType == 'Client') {
        this.tablePage.currentPage = val
        this.tableData = this.tableTotalData.slice((this.tablePage.currentPage - 1) * this.tablePage.pageSize, this.tablePage.currentPage * this.tablePage.pageSize)
        this.tablePage.total = this.tableTotalData.length
        return
      }
    },
    // 表格按钮操作
    tableButton(prop, row) {
      console.log('table prop is: ' + prop + ', table row is: ' + JSON.stringify(row))
    },
    // simpleData自定义事件
    simpleButton(prop) {
      console.log('prop is: ' + prop)
      this.dialogVisible = true
      this.dialogSimpleOption = {}
      this.dialogTableOptions = {}
      this.mathRandom = Math.random() * 10
      // 短信发送
      if (prop === 'personal-shortMessage-send') {
        this.dialogTableFlag = 'form'
        this.content = ''
        this.dialogTitle = this.dialogOption.saveShortMessage.title
        this.dialogFormOption = this.dialogOption.saveShortMessage.formOptions
      }
      // 历史短信查询
      else if (prop === 'personal-shortMessage-searchHistory') {
        this.dialogTableFlag = 'table'
        this.dialogTitle = this.dialogOption.shortMessageList.title
        this.dialogTableOptions = this.dialogOption.shortMessageList.tableOptions
        this.shortHistoryParams = {
          'phone': sessionStorage.getItem('customerPhone'),
          'transferDate': [new Date(new Date().setDate(new Date().getDate() - 5)).Format('yyyyMMdd'), new Date().Format('yyyyMMdd')],
          'currentPage': 1,
          'pageSize': 20
        }
        this.getShortMessageList()
      }
    },
    dialogSearch(params, done) {
      console.log('short message params: ' + JSON.stringify(params))
      Object.keys(params).forEach(keys => {
        if (params[keys]) {
          this.shortHistoryParams[keys] = params[keys]
        }
      })
      if (params.transferDate) {
        if (Utils.dateRange(params.transferDate[0], params.transferDate[1]) > 365) {
          window.globalUiKit.notify('提示', '交易日期范围不能超过一年！', 'error')
          done()
          return
        }
      }
      this.getShortMessageList()
      if (done) {
        done()
      }
    },
    dialogSearchClear() {
      this.shortHistoryParams = {
        'phone': sessionStorage.getItem('customerPhone'),
        'transferDate': [new Date(new Date().setDate(new Date().getDate() - 5)).Format('yyyyMMdd'), new Date().Format('yyyyMMdd')],
        'currentPage': 1,
        'pageSize': 20
      }
    },
    // 根据业务类型获取短信模板
    getMessageTemplate(value) {
      const params = {
        'columns': [{
          'cond': 0,
          'name': 'classify',
          'value': value
        }],
        'limit': 10000,
        'offset': 0
      }
      messageTemplate(params).then((res) => {
        if (res.data.code == 200) {
          this.msgTemplate = res.data.data.listData
        } else {
          this.msgTemplate = []
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 确认关闭弹框
    dialogSendMessage() {
      if (!this.content) {
        window.globalUiKit.notify('提示', '请先选择短信模板！', 'error')
        return
      }
      if (this.content.indexOf('userid=') > -1) {
        this.content = this.content.replace('userid=', 'userid=' + Constants.Agent.userId)
      }
      this.$confirm(this.content, '短信发送', {
        confirmButtonText: '发送',
        cancelButtonText: '取消',
        type: ''
      }).then(() => {
        const params = {
          'content': this.content,
          'phone': sessionStorage.getItem('customerPhone'),
          'agentName': Constants.Agent.agentName,
          'agentId': Constants.Agent.agentId,
          'smsType': '综合业务'
        }
        sendContentMessage(params).then(res => {
          if (res.data.code == 200) {
            window.globalUiKit.notify('提示', '短信发送成功！', 'success')
            this.saveShortMessageList('已发送')
            this.dialogVisible = false
          } else {
            window.globalUiKit.alert('短信发送失败', '失败原因：' + res.data.message + '；入参：' + JSON.stringify(params))
            this.saveShortMessageList('发送失败')
          }
        }).catch(error => {
          console.log(error)
          window.globalUiKit.alert('短信发送失败', '失败原因：' + error + '；入参：' + JSON.stringify(params))
          this.saveShortMessageList('发送失败')
        })
      }).catch(() => {
        console.log('取消发送！')
      })
    },
    // 保存短信记录接口
    saveShortMessageList(status) {
      const params = {
        'status': status,
        'businessType': this.selectVal.businessType,
        'content': this.content,
        'phone': sessionStorage.getItem('customerPhone'),
        'customerName': sessionStorage.getItem('accName'),
        'idType': sessionStorage.getItem('customerIdType'),
        'idNo': sessionStorage.getItem('customerIdNo'),
        'cardNo': sessionStorage.getItem('bankNo'),
        'sessionId': Constants.Model.sid,
        'agentName': Constants.Agent.agentName,
        'agentId': Constants.Agent.agentId
      }
      saveShortMessage(params).then((res) => {
        if (res.data.code == 200) {
          console.log('保存短信记录成功')
        } else {
          window.globalUiKit.alert('短信记录保存失败', '失败原因：' + res.data.message + '；入参：' + JSON.stringify(params))
        }
      }).catch(error => {
        window.globalUiKit.alert('短信记录保存失败', '失败原因：' + error + '；入参：' + JSON.stringify(params))
      })
    },
    // 获取短信历史记录接口
    getShortMessageList() {
      this.shortHistoryParams.pageSize = 20
      this.shortHistoryParams.currentPage = 1
      this.dialogTablePage.pageSize = 20
      this.dialogTablePage.currentPage = 1
      this.dialogTablePage.total = 0
      this.getShortMessageFun()
    },
    // 接口封装
    getShortMessageFun() {
      getShortMessage(this.shortHistoryParams).then((res) => {
        if (res.data.code == 200) {
          this.dialogTableData = res.data.data.resList
          this.dialogTablePage.total = res.data.data.total
        } else {
          this.dialogTableData = []
          this.dialogTablePage.total = 0
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 切换行数
    dialogSizeChange(val) {
      this.shortHistoryParams.pageSize = val
      this.shortHistoryParams.currentPage = 1
      this.dialogTablePage.pageSize = val
      this.dialogTablePage.currentPage = 1
      this.getShortMessageFun()
    },
    // 切换页码
    dialogCurrentChange(val) {
      this.shortHistoryParams.currentPage = val
      this.dialogTablePage.currentPage = val
      this.getShortMessageFun()
    }
  },
  // 当前组件路由守卫
  beforeRouteEnter(to, from, next) {
    next()
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  }
}
</script>

<style scoped>

  .el-breadcrumb {
    padding: 10px 0 !important;
  }

  .el-button--primary {
    margin-top: 5px !important;
  }

</style>
